<template>
  统一设置:

  <el-checkbox
    v-model="ruleChecked.required"
    label="必填"
    value="required"
    @change="requiredChange"
  />
  <el-checkbox
    v-model="ruleChecked.repeat"
    label="允许重复"
    value="repeat"
    @change="repeatChange"
  />

  <el-tabs v-model="activeName" type="border-card" class="rule_tabs">
    <el-tab-pane label="前端校验规则" name="WEB">
      <MonacoEdit v-model="rule" style="width: 800px" />
    </el-tab-pane>
    <el-tab-pane label="后端校验规则" name="SERVICE">
      <div style="color: brown" v-if="serviceRule === ''">
        注意:
        切换Json编辑器时需要有一个初始值,若无,请切换到文本或其他模类型添加初始值再切换会Json编辑器
      </div>
      <JsonEditView style="width: 800px" v-model="serviceRule" />
    </el-tab-pane>
  </el-tabs>
</template>
<script lang="ts" setup>
import JsonEditView from '@/views/template/util/JsonEditView.vue'
import MonacoEdit from '@/views/template/util/MonacoEdit.vue'
import { replaceLastChar } from '@/utils/str'
import { ref } from 'vue'
const rule = defineModel('rule')
const serviceRule = defineModel('serviceRule')
const activeName = ref('WEB')
const ruleChecked = ref({
  required: false,
  repeat: true
})
function requiredChange(value) {
  // 同步到json
  serviceRule.value.required = value
  syncRule()
}
function repeatChange(value) {
  // 同步到json
  serviceRule.value.repeat = value
  if (!value) {
    // 不允许重复字段须设为必填
    ruleChecked.value.required = true
    requiredChange(true)
  }
  syncRule()
}

function syncRule() {
  let tempRule = '() => [\r\n    {'
  for (const key in serviceRule.value) {
    const value = serviceRule.value[key]
    tempRule = tempRule.concat('\r\n        ').concat(key).concat(': ').concat(value).concat(',')
  }
  tempRule = replaceLastChar(tempRule, ',', '')
  rule.value = tempRule.concat(' \r\n    }\r\n]')
}
</script>
<style scoped>
.rule_tabs {
  height: 400px;
}
:deep(.jsoneditor-vue) {
  height: 300px !important;
}
</style>
